import CommonEventManager from '@ohos.commonEventManager'
import LogUtil from './LogUtil'

let mCommonEventSubscribeInfo = {
    events: ['BRIGHTNESS_VALUE_SYSTEM_UI']
}

let mCommonEventSubscriber = null;
let mCustomStatusSubscriberCallBack = null;

/**
 * broadcast
 */
export class SubscriberUtil {
    private TAG: string = `SubscriberUtil`
    /**
     * Send broadcast
     *
     * @param value - value
     * @param broadcastName - broadcastName
     */
    sendEvent(value, broadcastName) {
        let commonEventPublishData = {
            data: value
        };
        CommonEventManager.publish(broadcastName, commonEventPublishData, (err, data) => {
            LogUtil.error(this.TAG, `sendEvent  >> err = %{public}s`, JSON.stringify(err));
            LogUtil.debug(this.TAG, `sendEvent  >> data = %{public}s`, JSON.stringify(data));
        });
    }

    /**
     * Register to broadcast
     */
    registerStatusListener(pCommonEventSubscribeInfo?, pCallback?) {
        LogUtil.debug(this.TAG, `registerStatusListener start`)
        mCustomStatusSubscriberCallBack = pCallback
        var subscribeInfo = pCommonEventSubscribeInfo ? pCommonEventSubscribeInfo : mCommonEventSubscribeInfo
        CommonEventManager.createSubscriber(
            subscribeInfo,
        this.createStatusSubscriberCallBack.bind(this)
        )
        LogUtil.debug(this.TAG, `registerStatusListener end`)
    }

    createStatusSubscriberCallBack(err, data) {
        LogUtil.debug(this.TAG, `createStatusSubscriberCallBack  >> err = %{public}s  data = %{public}s`, JSON.stringify(err), JSON.stringify(data))
        mCommonEventSubscriber = data;
        CommonEventManager.subscribe(mCommonEventSubscriber, this.statusSubscriberCallBack.bind(this));
    }

    statusSubscriberCallBack(err, data) {
        LogUtil.debug(this.TAG, `createStatusSubscriberCallBack  >> err = %{public}s  data = %{public}s  event = %{public}s`, JSON.stringify(err), JSON.stringify(data), data.event)
        if (mCustomStatusSubscriberCallBack) {
            mCustomStatusSubscriberCallBack(err, data);
        }
        if (err) {
            LogUtil.error(this.TAG, `SubscriberUtil  >>  createStatusSubscriberCallBack  >> error = %{public}s`, JSON.stringify(err))
            return;
        }
    }

    /**
     * unRegister to broadcast
     */
    unSubscriberListener() {
        CommonEventManager.unsubscribe(mCommonEventSubscriber, () => {
            LogUtil.debug(this.TAG, 'unSubscriberListener')
        });
    }
}

let subscriberUtil = new SubscriberUtil();

export default subscriberUtil as SubscriberUtil;